#!/usr/bin/python
# author Yu
# 2023年06月19日
import socket
import sys

from tran import TransCode
import select


class Client:
    def __init__(self, ip, port):
        self.addr = (ip, port)
        self.trans = TransCode()

    def run(self):
        name = input('请输入昵称')
        client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client_socket.connect(self.addr)
        epoll = select.epoll()
        epoll.register(client_socket.fileno(), select.EPOLLIN)
        epoll.register(sys.stdin.fileno(), select.EPOLLIN)
        while True:
            events=epoll.poll(-1,2)
            for fd,event in events:
                if fd==client_socket.fileno():
                    data_bytes = client_socket.recv(128)
                    if data_bytes:
                        data = self.trans.encodes(data_bytes)
                        print(data)
                    else:
                        epoll.unregister(client_socket.fileno())
                        print("断开链接")
                        return
                elif fd==sys.stdin.fileno():
                    data = input()
                    data_bytes = self.trans.decodes(name+':'+data)
                    client_socket.send(data_bytes)
        client_socket.close()


client = Client('172.20.208.29', 9999)
client.run()
